(function( specs, $, undefined ) {

	var levels = [];
	var subSkill = 0;
	var slotMax = 30;
	var specId = -1;

	specs.setId = function ( id )
	{
		specId = id;
	}	
	specs.getId = function ()
	{
		return specId;
	}	
	function getSubMax(lvl)
	{
		if(lvl != undefined){
			if(lvl < 9){
				return 1;
			}else{
				return Math.floor(lvl/5);
			}
		}else{
			return 10;
		}
	}

	specs.changeMainJob = function ( id )
	{
		subSkill = 0;
		$('#sub-count').html(subSkill);
		var lvl = levels[id];
		$('#main-level').val(lvl);
		clearGrid();
		$('#sub-max').html(getSubMax(lvl));
		loadTemplate(id);
		/*specs.loadSkillList(id, lvl);*/
	}

	specs.changeSubJob = function ( id )
	{
		var lvl = levels[id];
		$('#sub-level').val(lvl);
		specs.loadSkillList(id, lvl);
	}

	specs.reset = function ()
	{
		subSkill = 0;
		$('#sub-count').html(subSkill);
		$('#sub-max').html(getSubMax());
		$('#main-level').val('');
		$('#sub-level').val('');
		clearGrid();
		specs.getLevels('reset', []);
	}

	specs.init = function ( ini )
	{

		subSkill = 0;
		specId = -1;
		$('sub-max').val(getSubMax());
		createMainGrid();
		specs.getLevels( 'reset', ini );
	}


	function clearGrid()
	{
		$('.slot').each( function(){
			$(this).html('');
		});
	}

	specs.adjustToMain = function ()
	{
		var main = $('#main-job').attr('name');
		var mainLvl = $('#main-level').val();
		levels[main] = mainLvl;

		//Adjust plain to main job
		//remove all the main job skill which are > the level
		adjustTemplateSkills(mainLvl);
		
		// adjust number of subjobskills
		adjustSubSkills(mainLvl);
	}

	specs.adjustToSub = function ()
	{

		var sub = $('#sub-job').attr('name');
		var subLvl = $('#sub-level').val();
		levels[sub] = subLvl;
		specs.loadSkillList( sub,  subLvl);
		//Adjust plain to sub job
		//rmove all the skill which are not leveL? need to think if necessary
	}

	function adjustTemplateSkills(lvl)
	{
		$('.templ').each( function(){
			//if(parseInt($(this).data( 'level' )) > lvl){
			if(parseInt($(this).data( 'skill' ).level) > lvl){
				$(this).remove();
			}
		});
	}

	function adjustSubSkills(lvl)
	{
		var subMax = getSubMax(lvl);
		$('#sub-max').html(subMax);
		
		if($('#sub-count').html() > subMax){
			$('#sub-count').html(subMax);
			subSkill = subMax;
		}
		var y = 0;
		for ( var i=1; i <= slotMax; i++ ) {
			var slotSkill = $('#slot_'+i+' > div');
			var slotSkillTemplate = slotSkill.data( 'template' );
			if(slotSkillTemplate == false){
				if(y+1 > subMax){
					slotSkill.remove();
				}
				y++;				
			}	
		}
	}

	specs.loadLevels = function (){
		specs.getLevels('', []);
	}
	specs.getLevels = function ( action , ini)
	{	
		levels = [];
		$("#status").html("<div class=\"center loader-gif\"></div>");
		$.post("./specs/xivspecs/get-levels.php", {action: action},
			function(data){
				for (var key in data){
					levels[data[key].id] = data[key].level
				}
				if(ini != []){
					levels[ini[1]] = ini[0];
				}
				var main = $('#main-job').attr('name');
				var sub = $('#sub-job').attr('name');
				if(main != -1){
					$("#abilityListContainer").html("<div style='margin-top:100px;' class=\"center loader-gif\"></div>");
					$('#main-level').val(levels[main].toString());
					adjustTemplateSkills(levels[main]);
					adjustSubSkills(levels[main]);
				}
				if(sub != -1){
					$("#abilityListContainer").html("<div style='margin-top:100px;' class=\"center loader-gif\"></div>");
					$('#sub-level').val(levels[sub].toString());
					specs.loadSkillList(sub, levels[sub]);
				}else{
					$("#abilityListContainer").html('');
				}
					
				$("#status").html('');			
			}
		, "json");
		

	}

	function createMainGrid()
	{
		for ( var i=1; i<=slotMax; i++ ) {
			$('<div id="slot_'+i+'" class="slot"></div>').data( 'slot', i ).appendTo( '#gridContainer-main' ).droppable( {
			  accept: '#abilityListContainer div, .skill, .templ',
			  hoverClass: 'hovered',
			  drop: handleSubDrop
			} );
		}
		$('#delete-area').droppable( {
		  accept: '#abilityListContainer div, .skill, .templ',
		  drop: handleDeleteDrop
		} );
	}

	specs.createTooltip = function(data){
			
		
			var skillHover = "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='10%' rowspan='3' align='left' valign='top'><img src='images/db/3/icon"+data.icon+".png' /></td> <td width='90%'><span style='font-size:15px;'><strong>"+data.name+"</strong></span></td></tr><tr><td>"+data.desc+"</td></tr><tr><td><strong>Lv. "+data.level+"</strong>";
			if(data.mp > 0){
				skillHover +=", MP. "+data.mp;
			}
			if(data.tp > 0){
				skillHover +=", TP. "+data.tp;
			}
			if(data.range > 0){
				skillHover +=", Range. "+data.range;
			}
			skillHover +="</td></tr></table>";
			return skillHover;
	}


	function loadTemplate(job)
	{
		// MAKE IT SMART SO DONT HAVE TO RESET GRID?
		$.post("./specs/xivspecs/get-template.php", {jobId: job, lvl: levels[job]},
			function(data){
				var i = 1;
				for (var key in data){
				
					var icon = $('<div class="templ"><img style="float:left;" class="spec-tooltip skillbox" src="images/db/3/icon'+data[key].icon+'.png" width="64" height="64" style="opacity:1;" name="'+ specs.createTooltip(data[key])+'"><span class="skilllv" style="color: #F4F4F4 !important;background-color: black;position:absolute;">'+data[key].level+'</span></div>')
						.data( 'skill', data[key] )
						//.data( 'skillId', data[key].id )
						.data( 'from', 'inside' )
						.data( 'template', true)
						//.data( 'level', data[key].level)
						.data( 'fromSlot', 'slot_'+i )
						.draggable( {
						  zIndex: 1000,
						  cursorAt: { top: 32, left: 32 },
						  revert: 'invalid',
						  drag: function(event, ui) { addWasteBin();},
						  stop: function(event, ui) { hideWasteBin(); }
						} );	
								
						
					
					$('#slot_'+i).html(icon);
					i++;
				}
				specs.refreshTooltip();
			}
		, "json");
	}



	specs.loadSkillList = function(job , lvl, name)
	{
		if(name == undefined){
			name= -1;
		}
		$("#abilityListContainer").html("<div style='margin-top:100px;' class=\"center loader-gif\"></div>");
		$.post("./specs/xivspecs/ability-list.php", {jobId: job, level: lvl, skillName: name},
			function(data){
				$("#abilityListContainer").html("");
				for (var key in data){
							
					$('<div class="skill" style="float:left;" ><img style="float:left;" class="spec-tooltip skillbox" src="images/db/3/icon'+data[key].icon+'.png" width="64" height="64" style="opacity:1;" name="'+specs.createTooltip(data[key])+'"><span class="skilllv" style="color:#000 !important;">'+data[key].level+'</span></div>')
						.data( 'skill', data[key] )
						//.data( 'skillId', data[key].id )
						.data( 'from', 'outside' )
						.data( 'template', false )
						//.attr( 'title', data[key].id )
						//.data( 'level', data[key].level)
						.appendTo( '#abilityListContainer' )
						.draggable( {
						  zIndex: 1000,
						  cursorAt: { top: 32, left: 32 },
						  revert: 'invalid',
						  helper: 'clone'
						} );
					
					if(data[key].search)
					{
						$('<div class="normal-text bold-text" style="margin-top: 12px;margin-left: 70px;">'+data[key].name+' </div>')
						.appendTo( '#abilityListContainer' )
						$('<div class="normal-text bold-text" style="margin-top: 5px;height: 52px;margin-left: 70px;opacity:0.5;font-size:10px;"> ( '+data[key].job+' ) </div>')
						.appendTo( '#abilityListContainer' )
					}else{
						$('<div class="normal-text bold-text" style="margin-top: 12px;height: 52px;margin-left: 70px;">'+data[key].name+'</div>')
						.appendTo( '#abilityListContainer' )
					}
				}
				specs.refreshTooltip();
			}
		, "json");
	}
	function handleDeleteDrop(event,ui)
	{
		hideWasteBin();
		var skilldata = ui.draggable.data( 'skill' );
		var template = ui.draggable.data( 'template' );
		var inside = ui.draggable.data( 'from');
		
		if(!template && inside == 'inside'){
			ui.draggable.remove();
			subSkill--;
			$('#sub-count').html(subSkill);
			
		}else{
			ui.draggable.draggable( 'option', 'revert', true );
			if(inside == 'inside'){
				$('#status').html('<div class="error">You can not remove template skills!</div>');
			}
		}
	}
	
	function handleSubDrop( event, ui ) 
	{
		var targetSlotId = $(this).attr( 'id' );
		var from = ui.draggable.data( 'from' );
		//var skillId = ui.draggable.data( 'skillId' );
		var skilldata = ui.draggable.data( 'skill' );
		var skillId = skilldata.id;
		//var level = ui.draggable.data( 'level' );
		var level = skilldata.level;
		var template = ui.draggable.data( 'template' );
		var replace = $('#'+targetSlotId+' > div');
		var replacedata = replace.data( 'skill' );
		if(replacedata != undefined){
			//var replaceLevel = replace.data( 'level' );
			var replaceLevel = replacedata.level;
			//var replaceSkillId = replace.data( 'SkillId' );
			var replaceSkillId = replacedata.id
			var replaceTemplate = replace.data( 'template' );
		}
		var newIcon;
		//ui.draggable.draggable( 'option', 'revert', false );
		var dont = false;
		
		if(from != 'inside'){
			dont = true;
			if(replacedata == undefined || replaceTemplate == false ){
				//Either new slot is empty, or we replace a non template
				//Bypass next test when replacing
				if($('#sub-max').html() > subSkill || replacedata != undefined){
					//Can have more subskills 
					if(replacedata == undefined){
						//Only update if not replacing
						subSkill++;
					}
					dont = false;
					$('#sub-count').html(subSkill);
					ui.draggable.draggable( 'option', 'revert', false );
					//ui.draggable.draggable( 'option', 'revert', false );
					// From outside make a copy to target
					newIcon = $(ui.draggable.clone());
				}else{
					$('#status').html('<div class="error">Too many sub skills already!</div>');
				}
			}else{
				$('#status').html('<div class="error">You cannot replace template skills!</div>');
			}
		}else{
			ui.draggable.draggable( 'option', 'revert', false );
			// From inside swap contents
			newIcon = ui.draggable;
			var insideSlotId = newIcon.data( 'fromSlot' );
			var insideSlot = $('#'+insideSlotId);
		    
			if(replacedata != undefined && targetSlotId != insideSlotId){
				replace.draggable( {
						  zIndex: 1000,
						  cursorAt: { top: 32, left: 32 },
						  revert: 'invalid',
						  drag: function(event, ui) { addWasteBin();},
						  stop: function(event, ui) { hideWasteBin(); }
						} );
				//replace.data( 'skillId', replaceSkillId );
				//replace.children("img").attr( 'title', specs.createTooltip(replacedata));
				replace.data( 'skill', replacedata );
				replace.data( 'from', 'inside' );
				replace.data( 'fromSlot', insideSlotId );
				//replace.data( 'level', replaceLevel );
				replace.data( 'template', replaceTemplate );
				//alert('Replace: fromSlot: '+insideSlotId+' | level: '+replaceLevel+' | template: '+replaceTemplate )
				insideSlot.html( replace );
			}
		}
		if(!dont){	
			//alert(insideSlotId)
			//alert(targetSlotId)
			if(targetSlotId != insideSlotId)
			{
				newIcon.draggable( {
							  zIndex: 1000,
							  cursorAt: { top: 32, left: 32 },
							  revert: 'invalid',
							  drag: function(event, ui) { addWasteBin();},
							  stop: function(event, ui) { hideWasteBin(); }
							} );
				//newIcon.children("img").attr( 'title', specs.createTooltip(skilldata));
				newIcon.data( 'skill', skilldata );
				//newIcon.data( 'skillId', skillId );
				newIcon.data( 'from', 'inside' );
				newIcon.data( 'fromSlot', targetSlotId );
				//newIcon.data( 'level', level );
				newIcon.data( 'template', template );
				$(this).html(newIcon);
				//reposition lvl text
				newIcon.position( { of: $(this), my: 'left top', at: 'left top' } );
				newIcon.css('z-index', 0);
				$('#'+targetSlotId+' .skilllv').css('position', 'absolute');
			//	alert('New: fromSlot: '+targetSlotId+' | level: '+level+' | template: '+template )
			}else{
				//Handle drop on yourself
				ui.draggable.draggable( 'option', 'revert', true );
			}
		}
		specs.refreshTooltip();
	}
	
	
	specs.saveSpec = function(){
		if($('#main-level').val() != "" && $('#main-level').val() != -1 && $('#main-job').attr('name') != -1){
			$("#status").html("<div class=\"center loader-gif\"></div>");
			$.post("./specs/xivspecs/save-spec.php", {jobId: $('#main-job').attr('name')
													, level: $('#main-level').val()
													, specId: specId
													, layout: getLayout()
													, description: $('#write-descr').val()
													},
				function(data){
					$("#status").html('');
					if(data.status == "1"){
						if (data.message == "INSERT"){
							//alert(data.id);
							specId = data.id;
							$('#status').html('<div class="success">Spec saved!</div>');
							$('#save-button').val('Update Spec');
						}else{
							$('#status').html('<div class="success">Spec updated!</div>');
						}
					}else{
						if(data.message == "TOOMANY"){
							$('#status').html('<div class="error">You saved too many specs already!</div>');
						}else{
							$('#status').html('<div class="error">There was an error please try again!</div>');
						}
					}
					
				}
			, "json");
		}else{
			$('#status').html('<div class="error">Please select a main job!</div>');
		}
	
	}
	
	specs.loadSpec = function(sId)
	{
		// MAKE IT SMART SO DONT HAVE TO RESET GRID?
		$.post("./specs/xivspecs/get-spec.php", {specId: sId},
			function(data){
				var i = 1;
			
				for (var key in data){
					if(data[key].template=="Y"){
						cl = "templ";
						templ = true;
						sty = "color: #F4F4F4 !important;background-color: black;position:absolute;";
					}else{
						subSkill++;
						cl = "skill";
						templ = false;
						sty = "color:#000 !important;;position:absolute;";
					}
					
					var icon = $('<div class="'+cl+'"><img style="float:left;" class="spec-tooltip skillbox" src="images/db/3/icon'+data[key].icon+'.png" width="64" height="64" style="opacity:1;" name="'+ specs.createTooltip(data[key])+'"><span class="skilllv" style="'+sty+'">'+data[key].level+'</span></div>')
						.data( 'skill', data[key] )
						//.data( 'skillId', data[key].id )
						.data( 'from', 'inside' )
						.data( 'template', templ)
						//.data( 'level', data[key].level)
						.data( 'fromSlot', 'slot_'+data[key].pos)
						.draggable( {
						  zIndex: 1000,
						  cursorAt: { top: 32, left: 32 },
						  revert: 'invalid',
						  drag: function(event, ui) { addWasteBin();},
						  stop: function(event, ui) { hideWasteBin(); }
						} );	
					
					$('#slot_'+data[key].pos).html(icon);
					i++;
				}
				specs.refreshTooltip();

				$('#sub-count').html(subSkill);
			}
		, "json");
	}
	
	
	function getLayout(){
		
		var layout = "";
		for ( var i=1; i <= slotMax; i++ ) {
			var slotSkill = $('#slot_'+i+' > div');
			var slotSkilldata = slotSkill.data( 'skill' );
			if(slotSkilldata != undefined){
				var slotSkillTemplate = slotSkill.data( 'template' );
				//var slotSkillId = slotSkill.data( 'skillId' );
				var slotSkillId = slotSkilldata.id;
				slotSkillTemplateChar = "Y";
				if(slotSkillTemplate == false){
					slotSkillTemplateChar = "N";
					
				}
				layout += slotSkillId+":"+i+":"+slotSkillTemplateChar+";";
			}
		}
		return layout.slice(0, -1);
	
	};
	
	specs.refreshTooltip = function (){
		$(".spec-tooltip").specTooltip({
			fixed: true, 
			position: 'bottom'
		});
	}
	
	
	specs.displayStatSkills = function ( da, w ){
		//da = eval('(' + da + ')');
		var lvl = $('#main-level').val();
		var lab = "+ Widen search";
		if(w == "true"){
			lvl = "1 - "+$('#main-level').val();
			lab = "- Lessen search";
			w = false;
		}else{
			w = true;
		}
		
		$("#statListContainer").html("<table style='width:100%;margin-top: 20px;margin-bottom: 30px;'> <tr> <td class='normal-text bold-text' style='font-size:10px;'> Other skills poeple have chosen as sub skills for:</td> </tr><tr> <td class='normal-text bold-text' style='font-size:10px;opacity:0.5'>"+$('#main-job').children('span').html()+" Lv. "+lvl+"<span class='blue-text cur-point' style='margin-left: 82px;' onclick='javascript:showSpecPop("+$('#main-job').attr('name')+", "+$('#main-level').val()+", \""+w+"\")'>"+lab+"</span></td> <tr> </table>");
		for (var key in da){
			$('<div class="skill" style="float:left;" ><img style="float:left;" class="spec-tooltip skillbox" src="images/db/3/icon'+da[key].icon+'.png" width="64" height="64" style="opacity:1;" name="'+specs.createTooltip(da[key])+'"><span class="skilllv" style="color:#000 !important;">'+da[key].level+'</span></div>')
				.data( 'skill', da[key] )
				.data( 'from', 'outside' )
				.data( 'template', false )
				.appendTo( '#statListContainer' )
				.draggable( {
				  zIndex: 1000,
				  cursorAt: { top: 32, left: 32 },
				  revert: 'invalid',
				  helper: 'clone'
				} );
			$('<div class="normal-text bold-text" style="margin-top: 12px;height: 52px;margin-left: 70px;">'+da[key].name+' <span style="opacity:0.5;">( '+da[key].skillName+' )</span></div><div class="normal-text bold-text" style="margin-top: -25px;height: 52px;margin-left: 85px;font-size: 10px;">Occurrences: '+da[key].skillCount+' <span style="opacity:0.5">( ~'+Math.round((da[key].skillCount/da[key].totalCount)*100)+'% )</span></div>')
				.appendTo( '#statListContainer' )
		}
		specs.refreshTooltip();
	}
	
	specs.generateMacro = function(){
		$("#abilityListContainer").html("");
		for ( var i=1; i<=slotMax; i++ ) {
		
			var slotSkill = $('#slot_'+i+' > div');
			var slotSkilldata = slotSkill.data( 'skill' );
			if(slotSkilldata != undefined){
				$('<div style="float:left;" ><span class="normal-text bold-text" style="font-size:10px">/eaction '+i+' \"'+slotSkilldata.name+'\"</span></div><br>').appendTo( '#abilityListContainer' );
			}
			
		}
	}
	
	function addWasteBin(){
		$('#delete-area').fadeIn();
		$('#status').html("");
	}
	function hideWasteBin(){
		$('#delete-area').fadeOut();
	}
	
	
}( window.specs = window.specs || {}, jQuery ));
